/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.login.policy;

import com.codemagi.login.model.IUser;
import com.codemagi.servlets.AppException;
import com.codemagi.util.Utils;

public class PasswordLengthPolicy implements IPasswordPolicy {

    private Integer minSize = null;
    private Integer maxSize = null;
    private String errorMessage; 
    
    public PasswordLengthPolicy(Integer minSize) {
	this.minSize = minSize;

	errorMessage = "Your password must be at least " + minSize + " characters in length.";
    }

    public PasswordLengthPolicy(Integer minSize, Integer maxSize) {
	this.minSize = minSize;
	this.maxSize = maxSize;

	errorMessage = "Your password must be between " + minSize + " and " + maxSize + " characters in length.";
    }

    /** 
     * Actually performs the policy check
     */
    public boolean check(IUser user, String newPassword) throws AppException {

	if (Utils.isEmpty(newPassword)) throw new AppException("Password is null");

	if (minSize != null && newPassword.length() < minSize) throw new AppException(errorMessage);

	if (maxSize != null && newPassword.length() > maxSize) throw new AppException(errorMessage);
	    
	return true;
    }

}
